package com.reebake.ideal.storage.entity;

import cn.hutool.core.util.StrUtil;
import org.springframework.http.MediaType;
import org.springframework.http.MediaTypeFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class BytesMultipartFile implements MultipartFile {
    private final byte[] bytes;
    private final String filename;
    private final String contentType;

    public BytesMultipartFile(String filename, byte[] bytes) {
        this(filename, null, bytes);
    }

    public BytesMultipartFile(String filename, String contentType, byte[] bytes) {
        this.filename = filename;
        this.contentType = StrUtil.isBlank(contentType) ? MediaTypeFactory.getMediaType(filename).orElse(MediaType.APPLICATION_OCTET_STREAM).toString() : contentType;
        this.bytes = bytes;
    }

    @Override
    public String getName() {
        return this.filename;
    }

    @Override
    public String getOriginalFilename() {
        return this.filename;
    }

    @Override
    public String getContentType() {
        return this.contentType;
    }

    @Override
    public boolean isEmpty() {
        return bytes == null || bytes.length == 0;
    }

    @Override
    public long getSize() {
        return bytes.length;
    }

    @Override
    public byte[] getBytes() {
        return bytes;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(bytes);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(dest);
            out.write(bytes);
        } catch (Exception e) {
            throw e;
        }finally {
            try {
                if(out != null) {
                    out.close();
                }
            }catch (Exception e) {

            }
        }
    }
}
